import { createRouter, createWebHashHistory } from "vue-router"
import { getJwt } from "@/api/jwt.js"

// 导入分开的路由配置
import pcRoutes from "./pc.js"
import mobileRoutes, { mobileBeforeEach, isMobileDevice } from "./mobile.js"

// 合并路由
const routes = [
    // PC端路由
    ...pcRoutes,

    // 移动端路由（添加前缀）- 修正后的写法
    ...mobileRoutes.map(route => {
        const mobileRoute = { ...route };

        // 处理路径
        mobileRoute.path = `/mobile${route.path}`;

        // 处理重定向
        if (route.redirect && typeof route.redirect === 'string') {
            mobileRoute.redirect = `/mobile${route.redirect}`;
        }

        // 确保meta中有isMobile标识
        mobileRoute.meta = {
            ...route.meta,
            isMobile: true
        };

        return mobileRoute;
    }),

    // 根路径重定向
    {
        name: "index",
        path: "/",
        redirect: (to) => {
            return isMobileDevice() ? "/mobile" : "/main"
        }
    },

    // 移动端根路径别名
    {
        path: "/mobile",
        redirect: "/mobile/"
    }
]

// 创建路由实例
const router = createRouter({
    routes,
    history: createWebHashHistory()
})


// 全局路由守卫
router.beforeEach((to, from, next) => {
    const isMobile = isMobileDevice()
    const isMobileRoute = to.meta?.isMobile || to.path.startsWith('/mobile')

    console.log('路由守卫:', { path: to.path, isMobile, isMobileRoute })

    if (isMobile && !isMobileRoute) {
        const jwt = getJwt()
        console.log('移动设备访问PC页面，重定向到移动端', to.path)
        next(jwt ? "/mobile/main" : "/mobile/login")
        return
    }

    if (!isMobile && isMobileRoute) {
        const jwt = getJwt()
        console.log('PC设备访问移动页面，重定向到PC端')
        next(jwt ? "/main" : "/login")
        return
    }

    // 根据路由类型调用相应的守卫逻辑
    if (isMobileRoute) {
        // 移动端路由守卫逻辑
        const jwt = getJwt()
        const requiresAuth = to.meta?.requiresAuth !== false

        if (requiresAuth && !jwt) {
            next('/mobile/login')
        } else if (!requiresAuth && jwt && to.path === '/mobile/login') {
            next('/mobile/main')
        } else {
            next()
        }
    } else {
        // PC端路由守卫逻辑
        const jwt = getJwt()
        if (jwt) {
            if (to.path === '/login') {
                next("/main")
            } else {
                next()
            }
        } else {
            if (to.path === '/login') {
                next()
            } else {
                next("/login")
            }
        }
    }
})

export default router